package com.kinsin.kinsinutil

import android.app.Activity
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.widget.Toast

/**
 * Toast 工具类
 * @author kinsin
 */
object ToastUtils {

    private var toast: Toast? = null

    /**
     * 显示 Toast（默认短时长）
     * @param context 建议使用 ApplicationContext 避免内存泄漏
     */
    fun showToast(context: Context, message: String, duration: Int = Toast.LENGTH_SHORT) {
        cancelPrevious()
        toast = createToast(context, message, duration)
        toast?.show()
    }

    /**
     * 安全显示 Toast（确保主线程且 context 有效）
     */
    fun showToastSafe(context: Context, message: String, duration: Int = Toast.LENGTH_SHORT) {
        val safeContext = context.applicationContext
        val toastRunnable = Runnable {
            cancelPrevious()
            toast = createToast(safeContext, message, duration)
            toast?.show()
        }

        if (context is Activity) {
            if (!context.isFinishing && !context.isDestroyed) {
                context.runOnUiThread { toastRunnable.run() }
            }
        } else {
            runOnUiThread(toastRunnable)
        }
    }

    private fun createToast(context: Context, message: String, duration: Int): Toast {
        return Toast.makeText(context, message, duration)
    }

    private fun runOnUiThread(action: Runnable) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            action.run()
        } else {
            Handler(Looper.getMainLooper()).post(action)
        }
    }

    private fun cancelPrevious() {
        toast?.cancel()
        toast = null
    }
}

// 扩展函数（支持空安全）
fun Context?.showToast(message: String, duration: Int = Toast.LENGTH_SHORT) {
    this?.let { ToastUtils.showToast(it.applicationContext, message, duration) }
}

fun Context?.showToastSafe(message: String, duration: Int = Toast.LENGTH_SHORT) {
    this?.let { ToastUtils.showToastSafe(it, message, duration) }
}